#!/usr/bin/python
"""Prints a notification of how recently a file has changed.

Specifically, looks for a game move status file that's newer than the
last login time and prints a status message about it. This is designed
for use in a login script."""

import datetime
import os
import sys


def DeltaToText(delta):
  """Converts a timedelta into human readable text."""

  if delta.days > 0:
    number = delta.days
    unit = ("day", "days")
  elif delta.seconds > 3600:
    number = int(delta.seconds / 3600)
    unit = ("hour", "hours")
  else:
    number = int(delta.seconds / 60)
    unit = ("minute", "minutes")

  if number == 1:
    unit_text = unit[0]
  else:
    unit_text = unit[1]

  return "%d %s" % (number, unit_text)

def main(argv):
  if len(argv) < 2:
    print "Usage: "
    print "  move-notify statusfile game message words"
    sys.exit(1)

  if argv[0] == "-nologin":
    login_test = False
    argv = argv[1:]
  else:
    login_test = True

  status_file_path = argv[0]
  message = " ".join(argv[1:])

  if login_test:
    home_path = os.getenv("HOME")
    last_login_path = home_path + "/.lastlogin"
    last_login_time = os.path.getmtime(last_login_path)
  else:
    last_login_time = None

  status_file_time = os.path.getmtime(status_file_path)

  # Unless we are skipping the last-login check, we will simply exit
  # if things haven't changed since the last recorded login.
  if login_test and status_file_time < last_login_time:
    return

  age = (datetime.datetime.now() -
         datetime.datetime.fromtimestamp(status_file_time))
  print "Last", message, DeltaToText(age), "ago"


if __name__ == "__main__":
  main(sys.argv[1:])
